from urllib.parse import urlencode
import json

from tornado import httpclient


class AsyncYunPian:

    def __init__(self, api_key):
        self.api_key = api_key

    async def send_single_sms(self, mobile, code):
        http_client = httpclient.AsyncHTTPClient()

        url = "https://sms.yunpian.com/v2/sms/single_send.json"
        text = "【转角的幸福】您的验证码是{}。如非本人操作，请忽略本短信".format(code)

        headers = {
            "Accept": "application/json;charset=utf-8;",
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;"
        }

        post_request = httpclient.HTTPRequest(url=url, method="POST", body=urlencode({
            'apikey': self.api_key,
            'mobile': mobile,
            'text': text
        }), headers=headers)

        try:
            res = await http_client.fetch(post_request)
        except:
            return False

        result = json.loads(res.body.decode("utf8"))
        if result.code == 0:
            return True
        return False


if __name__ == '__main__':
    import tornado
    from functools import partial

    io_loop = tornado.ioloop.IOLoop.current()
    yunpian = AsyncYunPian("ec336d122cd721ccfdec0de599d8dd57")
    # 将参数打包到函数中
    new_fun = partial(yunpian.send_single_sms, 17623603825, 1234)
    io_loop.run_sync(new_fun)
